package com.lazason.wib4android;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import weibo4andriod.Paging;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public abstract class BasicWib extends BasicActivity {
	Weibo weibo;
	String userId;
	String token;
	String tokenSecret;
	PopupWindow window;
	TimeLineTask timeLineTask;
	boolean isFirstWeibo = true;
	public static List<Map<String, Object>> data;
	public static List<Map<String, Object>> tempData;
	ListView listView;
	MyAdapter adapter;
	ProgressBar progressBar;
	LinearLayout layout;
	int page = 1;
	boolean isLoading = false;
	boolean isRefreshLoading = false;
	Paging paging;
	boolean firstLoadImage = true;
	AsyncImageLoader asyncImageLoader;
	protected ProgressDialog m_ProgressDialog = null;
	boolean needToNotifyDataChanged = false;
	boolean isFakeLoading;
	public static final int REFRESH = 1;
	public static final int MORE = 0;

	/**
	 * 设置布局显示属性
	 */
	private LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);
	/**
	 * 设置布局显示目标最大化属性
	 */
	private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.FILL_PARENT);

	LinearLayout loadingLayout;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		int lastItem = listView.getLastVisiblePosition();
		outState.putInt("lastItem", lastItem);
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");
		menu.add(0, 0, 0, "Forward");
		menu.add(0, 1, 1, "Comments");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem
				.getMenuInfo();

		/* Switch on the ID of the item, to get what the user selected. */
		switch (aItem.getItemId()) {
		case 1:
			/* Get the selected item out of the Adapter by its position. */
			Map info = (Map) listView.getAdapter().getItem(menuInfo.position);
			Log.d("WIB", " position " + menuInfo.position);
			Log.d("WIB", " screen_name " + info.get("username"));
			Log.d("WIB", " user id " + info.get("id"));
			Intent intent = new Intent();
			intent.putExtra("id", String.valueOf(info.get("weibo_id")));
			intent.putExtra("username", (String) info.get("username"));
			intent.putExtra("profile", (String) info.get("profile"));
			intent.putExtra("created_at", (String) info.get("created_at"));
			intent.putExtra("picture", (String) info.get("picture"));
			intent.putExtra("weibo", (String) info.get("weibo"));
			intent.setClass(this, PostCommentActivity.class);
			startActivity(intent);
			return true; /* true means: “we handled the event”. */
		}
		return false;
	}

	protected class TimeLineTask extends
			AsyncTask<Integer, Void, List<weibo4andriod.WeiboResponse>> {

		protected List doInBackground(Integer... page) {

			return processInBackground(page);
		}

		protected void onPostExecute(List friendsTimeline) {
			onPostProcessInBackground(friendsTimeline);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	void preLoadOriginalImage(String id, String url) {
		asyncImageLoader.loadDrawable(this, url, id, Thread.NORM_PRIORITY,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl, String id) {

					}
				});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
//		if (data != null) {
//
//			int lastItem = listView.getFirstVisiblePosition();
//
//			listView.setSelection(lastItem);
//		}
		// if(window==null){
		// Timer timer = new Timer();
		// timer.schedule(new initPopupWindow(), 100);
		// }
		super.onResume();
	}

	protected Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				showPopupWindow();
				break;
			}
		};
	};

//	private void showPopupWindow() {
//		LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		View v = lay.inflate(R.layout.imagebrowser, null);
//		ImageView iv = (ImageView) v.findViewById(R.id.originalImage);
//		iv.setFocusable(true);
//		iv.setClickable(true);
//		iv.setTag("visible");
//		iv.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View view) {
//				// TODO Auto-generated method stub
//				if ("visible".equals((String) ((ImageView) view).getTag())) {
//					((ImageView) view).setAlpha(125);
//					((ImageView) view).setTag("invisible");
//				} else {
//					((ImageView) view).setAlpha(255);
//					((ImageView) view).setTag("visible");
//				}
//			}
//
//		});
//		iv.setImageResource(R.drawable.icon);
//		// iv.setAlpha(20);
//		window = new PopupWindow(v, 50, 50);
//
//		window.setFocusable(false);
//		window.setTouchable(true);
//		window.setOutsideTouchable(true);
//		window.update();
//		window.showAtLocation(listView, Gravity.BOTTOM, 0, 0);
//
//	}

	protected class initPopupWindow extends TimerTask {
		@Override
		public void run() {

			Message message = new Message();
			message.what = 1;
			mHandler.sendMessage(message);

		}
	}

	protected void initActivity(Bundle savedInstanceState, int layoutResourceId) {
		setContentView(layoutResourceId);
		// progressBar = (ProgressBar) findViewById(R.id.timeline_progressbar);
		// progressBar = new ProgressBar(this,null,R.style.progress_style);

		// progressBar.setVisibility(View.INVISIBLE);
		listView = (ListView) findViewById(android.R.id.list);
		if (savedInstanceState != null) {
			int pos = savedInstanceState.getInt("lastItem", 0);
			listView.setSelection(pos);
		}

		LinearLayout layout = new LinearLayout(this);
		// 设置布局 水平方向
		layout.setOrientation(LinearLayout.HORIZONTAL);
		// 进度条
		progressBar = new ProgressBar(this);
		// 进度条显示位置
		progressBar.setPadding(0, 0, 15, 0);
		// 把进度条加入到layout中
		layout.addView(progressBar, mLayoutParams);
		// 文本内容
		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);
		// 把文本加入到layout中
		layout.addView(textView, FFlayoutParams);
		// 设置layout的重力方向，即对齐方式是
		layout.setGravity(Gravity.CENTER);
		// 设置ListView的页脚layout
		loadingLayout = new LinearLayout(this);
		loadingLayout.addView(layout, mLayoutParams);
		loadingLayout.setGravity(Gravity.CENTER);

		listView.addFooterView(loadingLayout);

		paging = new Paging();
		paging.setPage(page);
		userId = (String) this.getIntent().getStringExtra("userId");
		asyncImageLoader = new AsyncImageLoader();
		SharedPreferences mySharedPreferences = getSharedPreferences(WIB, mode);
		token = mySharedPreferences.getString("token", null);
		tokenSecret = mySharedPreferences.getString("tokenSecret", null);

		String style = mySharedPreferences.getString("style", null);
		if ("night".equals(style)) {
			MyApplication.style = "night";
			listView.setBackgroundResource(R.color.black);
		} else {
			MyApplication.style = "normal";
			listView.setBackgroundResource(R.color.white);
		}
		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

				if (totalItemCount != 0 && totalItemCount >= 20) {
					Log.d("onScroll", "totalItemCount:"+totalItemCount);
					if (firstVisibleItem + visibleItemCount >= totalItemCount-1 ) {
						// if(progressBar==null){
						// progressBar = new ProgressBar(BasicWib.this);
						// progressBar.setPadding(0, 0, 15, 0);
						//							
						// }
						// listView.addFooterView(progressBar);
						needToNotifyDataChanged = true;
						if (!isLoading) {
							
							if (data.size() > 0) {
								if (!isFakeLoading) {
									// progressBar.setVisibility(View.VISIBLE);
									fakeLoad();
									
									//needToNotifyDataChanged = false;
								}
							} else {
								// progressBar.setVisibility(View.VISIBLE);
								if (!isFakeLoading) {

									needToNotifyDataChanged = true;
									isLoading = true;
									// 开线程去下载网络数据
									loadingLayout.setVisibility(View.VISIBLE);
									timeLineTask = new TimeLineTask();
									timeLineTask.execute(MORE);
								}
							}
						} else {
							needToNotifyDataChanged = true;
						}
					} else if (data.size() <= 20
							&& (firstVisibleItem + visibleItemCount > data
									.size() - 10)) {
						if (!isLoading && tempData.size() == 0) {
							needToNotifyDataChanged = false;
							isLoading = true;
							// 开线程去下载网络数据
							loadingLayout.setVisibility(View.VISIBLE);
							timeLineTask = new TimeLineTask();
							timeLineTask.execute(MORE);
						}
					} else if (data.size() > 20
							&& (firstVisibleItem + visibleItemCount > data
									.size() - 40)) {
						if (!isLoading && tempData.size() == 0) {
							needToNotifyDataChanged = false;
							isLoading = true;
							// 开线程去下载网络数据
							loadingLayout.setVisibility(View.VISIBLE);
							timeLineTask = new TimeLineTask();
							timeLineTask.execute(MORE);
						}
					}

				}

			}

			@Override
			public void onScrollStateChanged(AbsListView paramAbsListView,
					int paramInt) {
				// TODO Auto-generated method stub

			}

		});
		registerForContextMenu(listView);
		listView.setFocusableInTouchMode(true);
		listView.requestFocus();
		// listView.addFooterView(progressBar);

		// Timer timer = new Timer();
		// timer.schedule(new initPopupWindow(), 100);
		data = new ArrayList<Map<String, Object>>();
		tempData = new ArrayList<Map<String, Object>>();
		weibo = OAuthConstant.getInstance().getWeibo();
		weibo.setToken(token, tokenSecret);
		try {
			weibo.getOAuthAccessToken(token, tokenSecret);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (window != null) {
			window.dismiss();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (window != null) {
			window.dismiss();
		}
		super.onDestroy();
	}

	protected List processInBackground(Integer... arg) {
		List friendsTimeline = null;
		try {

			friendsTimeline = readTimeline(arg[0]);

		} catch (WeiboException we) {
			we.printStackTrace();
			Log.d("BasicWib", we.toString());
			Log.d("BasicWib", we.getMessage());
			Log.d("BasicWib", "StatusCode:"+we.getStatusCode());

		} catch (Exception e) {
			e.printStackTrace();
			Log.d("BasicWib", e.toString());

		}
        if(friendsTimeline==null||friendsTimeline.size()==0){
        	if(arg[0]==MORE){
        	friendsTimeline =new  ArrayList<Map<String, Object>>();
        	} else{
        		friendsTimeline=null;
        	}
        	
        }
		return friendsTimeline;
	}

	protected void onPostProcessInBackground(List friendsTimeline) {
		
		if (friendsTimeline == null || friendsTimeline.size() == 0) {
			try{
			Toast.makeText(getApplicationContext(), "没有更多的微博",
					Toast.LENGTH_SHORT).show();
			 
			if(friendsTimeline == null){
				if (listView instanceof PullToRefreshListView) {
					((PullToRefreshListView) listView).onRefreshComplete();
				}
				isRefreshLoading=false;
				//resetRefreshLoading();
				
			}else{
				
				loadingLayout.setVisibility(View.GONE);
			}
			} catch(Exception e){
				
			}
			isLoading = false; 
		} else {
		try{
		if (m_ProgressDialog != null) {
			m_ProgressDialog.cancel();
			m_ProgressDialog.dismiss();
		}
		page++;

		addData(friendsTimeline);
		//改tempData为data
        if(data!=null&&data.size()>=40){
        	isRefreshLoading = true;
        }
		} catch(Exception e){
			
		}
        isLoading = false;
		}

	}

	protected abstract void addData(List list);

	protected abstract List readTimeline(int arg) throws WeiboException;

	void fakeLoad() {
		isFakeLoading = true;
		loadingLayout.setVisibility(View.VISIBLE);
		// 新建线程
		new Thread() {

			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					// TODO: handle exception
				}

				// 向handler发消息
				handler.sendEmptyMessage(0);

			}
		}.start();

	}

	/**
	 * 用Handler来更新UI
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// listView.removeFooterView(progressBar);
			// progressBar.setVisibility(View.INVISIBLE);
			// 更新UI
			data.addAll(tempData);
			adapter.notifyDataSetChanged();
			loadingLayout.setVisibility(View.GONE);
			tempData.clear();
			isFakeLoading = false;
		}
	};
	protected void showPopupWindow() {
		LinearLayout layout = new LinearLayout(this); 
		ImageView imageView = new ImageView(this);
		layout.addView(imageView);
		TextView refresh =new TextView(this);
		refresh.setText("刷新");
		layout.addView(refresh);
		imageView.setFocusable(true);
		imageView.setClickable(true);
		imageView.setTag("visible");
		imageView.setAlpha(20);
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				 
				refresh();
			}

		});
		imageView.setImageResource(R.drawable.icon);
		// iv.setAlpha(20);
		window = new PopupWindow(layout, 100, 100);

		window.setFocusable(false);
		window.setTouchable(true);
		window.setOutsideTouchable(true);
		window.update();
		window.showAtLocation(findViewById(layoutResource), Gravity.BOTTOM, -200, 0);

	}
	protected void showOrDismissWindow(){
	 if (window != null) {  
         if (window.isShowing())  
        	 window.dismiss();  
         else {  
        	 showPopupWindow();
         }  
     }  
	}
    abstract void refresh();
    
    void resetRefreshLoading(){
    	new Thread() {

			@Override
			public void run() {
				try {
					Thread.sleep(5000);
				} catch (Exception e) {
					// TODO: handle exception
				}

				isRefreshLoading=false;

			}
		}.start();
    }

}
